/***********************************************************************************************************
============================================================================================================
 Bits Download Manager
 http://www.codeplex.com/BITSDownloadMgr

 Component:BITSDownloadMgr.Interop
 File Name:CopyManager.cs
 
 
============================================================================================================
 Copyright (C) 2004-2007 Microsoft Corporation

 This source is subject to the Microsoft Public License (Ms-PL).
 See http:www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
 All other rights reserved.

 THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
 OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
 LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
 FITNESS FOR A PARTICULAR PURPOSE.
============================================================================================================
***********************************************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using BitsDownloadMgr.Interop;
using System.Collections.ObjectModel;

namespace BitsDownloadMgr.Interop
{
	public sealed class CopyManager : IDisposable
	{
		private IBackgroundCopyManager _nativeManager;


        #region Events
        public event EventHandler<JobCreatedEventArgs> JobCreated;
        private void OnJobCreated(CopyJob newJob)
        {
            if (JobCreated != null)
            {
                JobCreated.BeginInvoke(this, new JobCreatedEventArgs(newJob), null, null ); 
            }
        }
        #endregion 

        public CopyManager()
		{
			_nativeManager = (IBackgroundCopyManager)new BackgroundCopyManager();
		}
		/// <summary>
		/// Creates a new transfer job
		/// </summary>
		/// <returns>
		/// Reference to the newly created job.  
		/// </returns>
		public CopyJob CreateJob(string displayName, string description, BitsJobType jobType, BitsJobPriority priority)
		{
			Guid jobGuid; IBackgroundCopyJob job;
			_nativeManager.CreateJob(displayName, jobType, out jobGuid, out job);
			CopyJob newJob = new CopyJob(jobGuid, job);
			newJob.Description = description;
			newJob.Priority = priority;
            OnJobCreated(newJob); 
			return newJob;
		}

		public Collection <CopyJob> GetJobs()
		{
			return GetJobs(BitsEnumJobType.CurrentUser);
		}

		public Collection<CopyJob> GetJobs(BitsEnumJobType types)
		{

			IEnumBackgroundCopyJobs jobsEnumerator = null;
			try
			{
				//Get our enumerator 
				_nativeManager.EnumJobs(Convert.ToUInt32(types), out jobsEnumerator);
				//Get the count of jobs.  
				uint jobCount;
				jobsEnumerator.GetCount(out jobCount);
				Collection<CopyJob> jobList = new Collection<CopyJob>();
				//Get each job from the enumerator.  
				for (int i = 0; i < jobCount; i++)
				{
					IBackgroundCopyJob currentJob; uint jobFetched;
					jobsEnumerator.Next(1, out currentJob, out jobFetched);
					//make sure it's there before we add to the array.  
					if (jobFetched == 1)
					{
						CopyJob newJob = new CopyJob(currentJob);
						jobList.Add(newJob);
					}
				}
				return jobList;
			}
			finally
			{
				if (jobsEnumerator != null)
				{
					System.Runtime.InteropServices.Marshal.ReleaseComObject(jobsEnumerator);
				}
			}
		}

		public void CancelAllJobs()
		{
			CancelAllJobs(BitsEnumJobType.CurrentUser);
		}
		public void CancelAllJobs(BitsEnumJobType types)
		{
			Collection<CopyJob> jobs = GetJobs(types);
			foreach (CopyJob currentJob in jobs)
			{
				currentJob.Cancel();
			}
		}

		public CopyJob GetJob(Guid jobGuid)
		{
			IBackgroundCopyJob nativeJob; 
			_nativeManager.GetJob(ref jobGuid, out nativeJob);
			return new CopyJob(nativeJob); 

		}

		#region CleanUp Code
		#region IDisposable Members


		void Dispose(bool disposing)
		{
			if (_nativeManager != null)
			{
				System.Runtime.InteropServices.Marshal.ReleaseComObject(_nativeManager);
			}
		}
		void IDisposable.Dispose()
		{
			Dispose(true); 
			GC.SuppressFinalize(this);
		}

		#endregion
		~CopyManager()
		{
			Dispose(false); 
		}
		#endregion
	}

    public sealed class JobCreatedEventArgs : EventArgs
    {
        internal JobCreatedEventArgs(CopyJob newJob)
        {
            this._newJob = newJob; 
        }

        private CopyJob _newJob;
        public CopyJob NewJob
        {
            get { return _newJob; }
        }

    }
}

